import redis
import json

pool = redis.ConnectionPool(host='127.0.0.1', port=6379)


class MyRedis(redis.Redis):
    """
    自定义redis类
    """

    def hset_list_append(self, key, value, data):
        """
        value列表append
        :param key:
        :param value:
        :param data:
        :return:
        """
        lst = json.loads(self.hget(key, value))
        lst.append(data)
        self.hset(key, value, json.dumps(lst))

    def hset_list_remove(self, key, value, data):
        """
        value列表remove
        :param key:
        :param value:
        :param data:
        :return:
        """
        lst = json.loads(self.hget(key, value))
        lst.remove(data)
        self.hset(key, value, json.dumps(lst))

    def hget_obj(self, key, value):
        """
        value列表值
        :param key:
        :param value:
        :return:
        """
        return json.loads(self.hget(key, value))

    def hget_list_head(self, key, value, index=0):
        """
        value列表取值
        :param key:
        :param value:
        :param index:
        :return:
        """
        return json.loads(self.hget(key, value))[index]

    def hset_dict_setattr(self, key, value, k, v):
        """
        value字典append
        :param key:
        :param value:
        :param k:
        :param v:
        :return:
        """
        dic = json.loads(self.hget(key, value))
        dic[k] = v
        self.hset(key, value, json.dumps(dic))

    def hset_dict_pop(self, key, value, k):
        """
        value字典pop
        :param key:
        :param value:
        :param k:
        :return:
        """
        dic = json.loads(self.hget(key, value))
        dic.pop(k)
        self.hset(key, value, json.dumps(dic))

    def hget_dict_getattr(self, key, value, k):
        """
        value字典取值
        :param key:
        :param value:
        :param k:
        :return:
        """
        return json.loads(self.hget(key, value)).get(k)


# 单例模式
r = MyRedis(connection_pool=pool)

